<template>
  <div class="p-2">
    <el-row :gutter="10">
      <el-col :span="24" class="card-box">
        <el-card shadow="hover">
          <template v-slot:header>
            <Monitor style="width: 1em; height: 1em; vertical-align: middle" />
            <span style="vertical-align: middle"> Websocket：当前状态</span>
          </template>
          <el-descriptions border>
            <el-descriptions-item label="前端开启" label-width="160px">
              {{ frontEnabled }}
            </el-descriptions-item>
            <el-descriptions-item label="后端开启" label-width="160px">
              {{ backendEnabled }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="hover" style="margin-top: 10px">
          <template v-slot:header>
            <Odometer style="width: 1em; height: 1em; vertical-align: middle" />
            <span style="vertical-align: middle"> Websocket：直接发送</span>
          </template>
          <el-input v-model="sendMessage" type="textarea" :rows="6" style="width: 80%" placeholder="请输入需要发送的消息"></el-input>
          <template v-slot:footer>
            <el-tooltip content="向所有链接了Websocket的会话发送消息" placement="top">
              <el-button
                type="danger"
                icon="chat-line-square"
                style="float: right; margin: -10px 5px 8px 5px"
                @click="handleSendAll"
                :disabled="!frontEnabled || !backendEnabled"
              >
                全部发送
              </el-button>
            </el-tooltip>
            <el-tooltip content="直接向连接了Websocket的会话发送消息" placement="top">
              <el-button
                type="primary"
                icon="chat-square"
                style="float: right; margin: -10px 5px 8px 5px"
                @click="openSendUserSelect"
                :disabled="!frontEnabled || !backendEnabled"
              >
                发送
              </el-button>
            </el-tooltip>
          </template>
        </el-card>

        <el-card shadow="hover" style="margin-top: 10px">
          <template v-slot:header>
            <PieChart style="width: 1em; height: 1em; vertical-align: middle" />
            <span style="vertical-align: middle"> Websocket：订阅发布</span>
          </template>
          <el-input v-model="publishTopic" style="width: 40%; margin: 0 20px 10px 0" placeholder="请输入主题" maxlength="50" />
          <span style="color: red">*如果不输入主题，则使用全局主题global:websocket。该主题已订阅</span>
          <el-input v-model="publishMessage" type="textarea" :rows="6" style="width: 80%" placeholder="请输入需要发送的消息"></el-input>
          <template v-slot:footer>
            <el-tooltip content="发布到指定topic，所有订阅的会话都能收到" placement="top">
              <el-button
                type="danger"
                icon="chat-line-square"
                style="float: right; margin: -10px 5px 8px 5px"
                @click="handlePublishAll"
                :disabled="!frontEnabled || !backendEnabled"
              >
                全部发布
              </el-button>
            </el-tooltip>
            <el-tooltip content="发布到指定topic，同时指定接收人" placement="top">
              <el-button
                type="primary"
                icon="chat-square"
                style="float: right; margin: -10px 5px 8px 5px"
                @click="openPublishUserSelect"
                :disabled="!frontEnabled || !backendEnabled"
              >
                发布
              </el-button>
            </el-tooltip>
            <el-tooltip content="订阅指定topic的消息" placement="top">
              <el-button
                type="danger"
                icon="chat-line-square"
                style="float: right; margin: -10px 5px 8px 5px"
                @click="handleSubscribe"
                :disabled="!frontEnabled || !backendEnabled"
              >
                订阅
              </el-button>
            </el-tooltip>
          </template>
        </el-card>

        <UserSelect ref="sendUserRef" :multiple="false" :data="selectSendUserId" @confirm-call-back="afterSelectSendUser"></UserSelect>
        <UserSelect ref="publishUserRef" :data="selectPublishUserIds" @confirm-call-back="afterSelectPublishUser"></UserSelect>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Cache" lang="ts">
import { Monitor, Odometer, PieChart } from '@element-plus/icons-vue';
import UserSelect from '@/components/UserSelect/index.vue';
import { ref } from 'vue';
import { wsSend, wsSendAll, wsSubscribe, wsPublish, wsPublishAll, wsEnabled } from '@/api/demo/message/websocket';
import { UserVO } from '@/api/system/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const frontEnabled = ref<boolean>(import.meta.env.VITE_APP_WEBSOCKET === 'true');
const backendEnabled = ref<boolean>(false);

const selectSendUserId = ref<number | string>();
const selectPublishUserIds = ref<(number | string)[]>();
const sendUserRef = ref<InstanceType<typeof UserSelect>>();
const publishUserRef = ref<InstanceType<typeof UserSelect>>();

const sendMessage = ref<string>();
const publishTopic = ref<string>();
const publishMessage = ref<string>();

const openSendUserSelect = () => {
  sendUserRef.value.open();
};

const openPublishUserSelect = () => {
  publishUserRef.value.open();
};

const afterSelectSendUser = (data: UserVO[]) => {
  if (data && data.length > 0) {
    selectSendUserId.value = data[0].userId;
  }
  handleSend();
};

const afterSelectPublishUser = (data: UserVO[]) => {
  if (data && data.length > 0) {
    selectPublishUserIds.value = data.map((item) => item.userId);
  }
  handlePublish();
};

const handleSend = async () => {
  if (!selectSendUserId.value) {
    proxy?.$modal.msgWarning('请选择发送人员');
    return;
  }
  if (!sendMessage.value) {
    proxy?.$modal.msgWarning('请输入发送信息');
    return;
  }
  await wsSend(selectSendUserId.value, sendMessage.value);
  selectSendUserId.value = undefined;
  proxy?.$modal.msgSuccess('发送成功');
};

const handleSendAll = async () => {
  if (!sendMessage.value) {
    proxy?.$modal.msgWarning('请输入发送信息');
    return;
  }
  await wsSendAll(sendMessage.value);
  proxy?.$modal.msgSuccess('发送成功');
};

const handleSubscribe = async () => {
  await wsSubscribe(publishTopic.value);
  proxy?.$modal.msgSuccess('订阅成功');
};

const handlePublish = async () => {
  if (!publishMessage.value) {
    proxy?.$modal.msgWarning('请输入发送信息');
    return;
  }
  if (!publishTopic.value) {
    publishTopic.value = 'global:websocket';
  }
  await wsPublish(publishTopic.value, selectPublishUserIds.value, publishMessage.value);
  selectPublishUserIds.value = [];
  proxy?.$modal.msgSuccess('发布成功');
};

const handlePublishAll = async () => {
  if (!publishMessage.value) {
    proxy?.$modal.msgWarning('请输入发送信息');
    return;
  }
  if (!publishTopic.value) {
    publishTopic.value = 'global:websocket';
  }
  await wsPublishAll(publishTopic.value, publishMessage.value);
  proxy?.$modal.msgSuccess('发布成功');
};

onMounted(() => {
  nextTick(() => {
    wsEnabled().then((res) => {
      backendEnabled.value = res.data;
      if (!(backendEnabled.value && frontEnabled.value)) {
      }
    });
  });
});
</script>
